package team.lourd.network.system.utils.web;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.net.ssl.SSLContext;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;
import net.sf.json.processors.JsonValueProcessor;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

/**
 * API调用工具
 *
 * @author JADemo
 * @date 2019/2/21 10:00
 */
public class HttpUtil {
    // JSON序列化规则
    public static JsonConfig getJsonConfig() {
        JsonConfig jsonConfig = new JsonConfig();
        // 设置Integer默认值为null,而不是0
        jsonConfig.registerDefaultValueProcessor(Integer.class,
                new DefaultValueProcessor() {
                    public Object getDefaultValue(Class type) {
                        return null;
                    }
                });
        // 设置接受的日期格式 'yyyy-MM-dd'
        jsonConfig.registerJsonValueProcessor(Date.class,
                new JsonValueProcessor() {
                    private String pattern = "yyyy-MM-dd";

                    public Object processArrayValue(Object value, JsonConfig config) {
                        return process(value);
                    }

                    public Object processObjectValue(String key, Object value, JsonConfig config) {
                        return process(value);
                    }

                    private Object process(Object value) {
                        if (value instanceof Date) {
                            SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.UK);
                            return sdf.format(value);
                        }
                        return value;
                    }

                });
        return jsonConfig;
    }

    // 调用GET,返回JSON
    public static JSONObject doGetJson(String url)
            throws ClientProtocolException, IOException {
        JSONObject jsonObject = null;
        HttpClient httpClient = createSSLClientDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.fromObject(result, getJsonConfig());
        }
        httpGet.releaseConnection();
        return jsonObject;
    }

    // 调用GET,无返回
    public static void doGetJsonReturnNull(String url)
            throws ClientProtocolException, IOException {
        HttpClient httpClient = createSSLClientDefault();
        HttpGet httpGet = new HttpGet(url);
        httpClient.execute(httpGet);
        httpGet.releaseConnection();
    }
    // 调用POST,返回JSON
    public static JSONObject doPostJsonAddObject(String url, Object object)
            throws ClientProtocolException, IOException {
        JSONObject jsonObject = null;
        // System.out.println(((Employee)object).toString());
        HttpClient httpClient = createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        String strJson = JSONObject.fromObject(object, getJsonConfig())
                .toString();
        httpPost.setEntity(new StringEntity(strJson, "UTF-8"));
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            // jsonObject = JSONObject.fromObject(result);
        }
        httpPost.releaseConnection();
        return jsonObject;
    }

    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
                    null, new TrustStrategy() {
                        // 信任所有
                        public boolean isTrusted(X509Certificate[] chain,
                                                 String authType) throws CertificateException {
                            return true;
                        }
                    }).build();
            SSLConnectionSocketFactory ssl = new SSLConnectionSocketFactory(
                    sslContext);
            return HttpClients.custom().setSSLSocketFactory(ssl).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }
}
